<template>
  <view class="devices-page">
    <!-- 简化的搜索栏 -->
    <view class="search-section">
      <u-search 
        v-model="searchKeyword"
        placeholder="搜索设备名称、品牌或型号"
        @search="handleSearch"
        @clear="handleClear"
        :show-action="false"
        shape="round"
        bg-color="#f8f9fa"
      />
    </view>

    <!-- 设备列表 -->
    <scroll-view 
      scroll-y 
      class="list-container"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      @refresherrefresh="onRefresh"
      :refresher-triggered="refreshing"
    >
      <view class="device-list">
        <view 
          v-for="device in deviceList" 
          :key="device.id"
          class="device-card"
          @click="goToDetail(device.id)"
        >
          <!-- 设备图片 -->
          <view class="device-image-container">
            <image 
              :src="device.images?.[0] || '/static/placeholder-device.png'" 
              class="device-image"
              mode="aspectFill"
            />
            <view class="image-overlay">
              <view class="status-badge" :class="getStatusClass(device.status)">
                {{ getStatusText(device.status) }}
              </view>
              <view class="favorite-btn" @click.stop="toggleFavorite(device)">
                <u-icon 
                  :name="device.isFavorite ? 'heart-fill' : 'heart'" 
                  :color="device.isFavorite ? '#ff6b6b' : '#fff'"
                  size="18"
                />
              </view>
            </view>
          </view>
          
          <!-- 设备信息 -->
          <view class="device-content">
            <view class="device-header">
              <text class="device-title">{{ device.title }}</text>
              <text class="device-brand">{{ device.brand }} {{ device.model }}</text>
            </view>
            
            <view class="device-specs" v-if="device.specifications">
              <text class="spec-item" v-for="(value, key) in getMainSpecs(device.specifications)" :key="key">
                {{ key }}: {{ value }}
              </text>
            </view>
            
            <view class="device-footer">
              <view class="price-section">
                <text class="price-label">日租金</text>
                <text class="price-value">¥{{ device.dailyRent }}</text>
                <text class="price-unit">/天</text>
              </view>
              <view class="rent-info">
                <text class="rent-days">{{ device.minRentDays }}-{{ device.maxRentDays }}天</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && deviceList.length > 0">
        <u-loadmore :status="loadStatus" />
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-if="deviceList.length === 0 && !loading" class="empty-state">
      <image src="/static/empty-devices.png" class="empty-image" />
      <text class="empty-title">暂无设备</text>
      <text class="empty-desc">试试搜索其他关键词</text>
      <u-button type="primary" @click="resetSearch">重新搜索</u-button>
    </view>
  </view>
</template>

<script>
import apiService from '@/api/index.js'

export default {
  data() {
    return {
      searchKeyword: '',
      deviceList: [],
      totalCount: 0,
      loading: false,
      refreshing: false,
      loadStatus: 'more',
      
      // 分页
      page: 1,
      pageSize: 10,
      hasMore: true
    }
  },
  
  onLoad(options) {
    // 处理从首页传来的搜索关键词
    if (options.keyword) {
      this.searchKeyword = decodeURIComponent(options.keyword)
    }
    
    this.initPage()
  },
  
  onShow() {
    // 检查是否刚刚登录成功，如果是则延迟更新收藏状态
    const justLoggedIn = uni.getStorageSync('just_logged_in')
    if (justLoggedIn) {
      setTimeout(() => {
        this.updateFavoriteStatus()
      }, 1500)
    } else {
      // 每次显示时刷新收藏状态
      this.updateFavoriteStatus()
    }
    
    // 监听来自首页的搜索事件
    uni.$on('searchFromHome', this.handleSearchFromHome)
  },
  
  onHide() {
    // 移除事件监听
    uni.$off('searchFromHome', this.handleSearchFromHome)
  },
  
  methods: {
    async initPage() {
      // 加载设备列表
      await this.loadDeviceList()
    },
    
    async loadDeviceList(isRefresh = false) {
      if (this.loading) return
      
      try {
        this.loading = true
        this.loadStatus = 'loading'
        
        if (isRefresh) {
          this.page = 1
          this.hasMore = true
        }
        
        const params = {
          page: this.page,
          limit: this.pageSize
        }
        
        // 只有当搜索关键词不为空时才添加keyword参数
        if (this.searchKeyword && this.searchKeyword.trim()) {
          params.keyword = this.searchKeyword.trim()
        }
        
        console.log('🔍 搜索参数:', params)
        
        const response = await apiService.device.getDeviceList(params)
        console.log('📋 设备列表响应:', response)
        
        const data = response.data || response
        const devices = data.items || data.list || []
        const total = data.total || 0
        
        if (isRefresh) {
          this.deviceList = devices
        } else {
          this.deviceList = [...this.deviceList, ...devices]
        }
        
        // 检查收藏状态
        await this.checkDevicesFavoriteStatus(devices)
        
        this.totalCount = total
        this.hasMore = devices.length === this.pageSize && this.deviceList.length < total
        
        if (!this.hasMore) {
          this.loadStatus = 'nomore'
        } else {
          this.loadStatus = 'more'
        }
        
        this.page += 1
        
      } catch (error) {
        console.error('加载设备列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.loadStatus = 'more'
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 搜索处理
    handleSearch() {
      console.log('🔍 搜索关键词:', this.searchKeyword)
      this.loadDeviceList(true)
    },
    
    // 清空搜索
    handleClear() {
      this.searchKeyword = ''
      this.loadDeviceList(true)
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = ''
      this.loadDeviceList(true)
    },
    
    // 处理来自首页的搜索
    handleSearchFromHome(keyword) {
      console.log('🏠 接收到首页搜索关键词:', keyword)
      this.searchKeyword = keyword
      this.loadDeviceList(true)
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadDeviceList(true)
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadDeviceList()
      }
    },
    
    // 跳转到详情页
    goToDetail(deviceId) {
      uni.navigateTo({
        url: `/pages/devices/detail?id=${deviceId}`
      })
    },
    
    // 切换收藏状态
    async toggleFavorite(device) {
      try {
        // 检查用户是否登录
        const token = uni.getStorageSync('token')
        if (!token) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/auth/login'
            })
          }, 1500)
          return
        }

        // 防止重复点击
        if (device.favoriteLoading) {
          return
        }
        device.favoriteLoading = true

        const originalStatus = device.isFavorite
        console.log(`🔄 切换收藏状态: ${device.title} - 当前状态: ${originalStatus}`)

        if (originalStatus) {
          // 当前是收藏状态，执行取消收藏
          const response = await apiService.device.removeFavorite(device.id)
          console.log('❌ 取消收藏响应:', response)
          device.isFavorite = false
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
        } else {
          // 当前是未收藏状态，执行添加收藏
          const response = await apiService.device.addFavorite(device.id)
          console.log('❤️ 添加收藏响应:', response)
          device.isFavorite = true
          uni.showToast({
            title: '已添加收藏',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
        
        // 自定义错误消息，不显示后端的英文消息
        let message = '操作失败'
        if (error.message && error.message.includes('409')) {
          message = '收藏状态异常，请刷新后重试'
        } else if (error.message && error.message.includes('404')) {
          message = '设备不存在'
        } else if (error.message && error.message.includes('401')) {
          message = '请重新登录'
        }
        
        uni.showToast({
          title: message,
          icon: 'none'
        })
        
        // 发生错误时刷新收藏状态
        setTimeout(() => {
          this.updateFavoriteStatus()
        }, 1000)
      } finally {
        device.favoriteLoading = false
      }
    },
    
    // 批量检查设备收藏状态
    async checkDevicesFavoriteStatus(devices) {
      try {
        // 检查用户是否登录
        const token = uni.getStorageSync('token')
        if (!token || devices.length === 0) return

        const deviceIds = devices.map(device => device.id)
        const response = await apiService.device.checkMultipleFavorites(deviceIds)
        
        const favoriteStatus = response.data || response
        
        // 更新设备的收藏状态
        devices.forEach(device => {
          device.isFavorite = favoriteStatus[device.id] || false
        })
        
      } catch (error) {
        console.error('批量检查收藏状态失败:', error)
        // 如果检查失败，默认设置为未收藏
        devices.forEach(device => {
          device.isFavorite = false
        })
      }
    },

    // 更新收藏状态
    updateFavoriteStatus() {
      // 每次显示时重新检查所有设备的收藏状态
      if (this.deviceList.length > 0) {
        this.checkDevicesFavoriteStatus(this.deviceList)
      }
    },
    
    // 获取设备状态样式类
    getStatusClass(status) {
      const statusMap = {
        'AVAILABLE': 'available',
        'RENTED': 'rented',
        'MAINTENANCE': 'maintenance',
        'OFFLINE': 'offline'
      }
      return statusMap[status] || 'available'
    },
    
    // 获取设备状态文本
    getStatusText(status) {
      const statusMap = {
        'AVAILABLE': '可租用',
        'RENTED': '已租出',
        'MAINTENANCE': '维护中',
        'OFFLINE': '下线'
      }
      return statusMap[status] || '可租用'
    },
    
    // 获取主要规格参数
    getMainSpecs(specifications) {
      if (!specifications || typeof specifications !== 'object') return {}
      
      // 只显示前3个主要参数
      const mainKeys = ['capacity', 'power', 'voltage', 'weight', 'dimensions']
      const result = {}
      let count = 0
      
      for (const key of mainKeys) {
        if (specifications[key] && count < 3) {
          const label = this.getSpecLabel(key)
          result[label] = specifications[key]
          count++
        }
      }
      
      return result
    },
    
    // 获取规格参数标签
    getSpecLabel(key) {
      const labelMap = {
        'capacity': '处理量',
        'power': '功率',
        'voltage': '电压',
        'weight': '重量',
        'dimensions': '尺寸',
        'material': '材质',
        'temperature': '温度',
        'pressure': '压力'
      }
      return labelMap[key] || key
    }
  }
}
</script>

<style lang="scss" scoped>
.devices-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 16rpx 24rpx;
  border-bottom: 1rpx solid #eee;
}

.list-container {
  height: calc(100vh - 120rpx);
}

.device-list {
  padding: 0 24rpx;
}

.device-card {
  background: white;
  border-radius: 16rpx;
  margin: 16rpx 0;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 24rpx;
}

.device-image-container {
  position: relative;
  width: 200rpx;
  height: 150rpx;
  flex-shrink: 0;
}

.device-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 12rpx;
}

.status-badge {
  position: absolute;
  top: 8rpx;
  left: 8rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  color: white;
  
  &.available {
    background: #52c41a;
  }
  
  &.rented {
    background: #faad14;
  }
  
  &.maintenance {
    background: #ff4d4f;
  }
  
  &.offline {
    background: #d9d9d9;
  }
}

.favorite-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.device-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.device-header {
  .device-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    line-height: 1.4;
    margin-bottom: 8rpx;
    display: block;
  }
  
  .device-brand {
    font-size: 24rpx;
    color: #666;
    display: block;
  }
}

.device-specs {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  
  .spec-item {
    font-size: 22rpx;
    color: #888;
    background: #f5f5f5;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
  }
}

.device-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: auto;
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  
  .price-label {
    font-size: 22rpx;
    color: #888;
  }
  
  .price-value {
    font-size: 36rpx;
    font-weight: 600;
    color: #ff6b35;
  }
  
  .price-unit {
    font-size: 24rpx;
    color: #888;
  }
}

.rent-info {
  .rent-days {
    font-size: 22rpx;
    color: #666;
    background: #f0f0f0;
    padding: 8rpx 16rpx;
    border-radius: 12rpx;
  }
}

.load-more {
  padding: 32rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 60rpx;
  
  .empty-image {
    width: 240rpx;
    height: 180rpx;
    margin-bottom: 32rpx;
  }
  
  .empty-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .empty-desc {
    font-size: 28rpx;
    color: #888;
    margin-bottom: 48rpx;
    text-align: center;
    line-height: 1.6;
  }
}
</style>